#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import requests, time, json, pymysql
from django.conf import settings

from vouchers.models import AliDiscountCoupon
from equity_mall.utils.utils import random_str
from equity_admin.utils import rsa_long_encrypt


def get_data(stock_id, pub_key_str, mch_id, serial_no):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/{stock_id}/use-flow'
    nonce_str = random_str()
    timestamp = int(time.time())
    message = f'GET\n/v3/marketing/favor/stocks/{stock_id}/use-flow\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt(pub_key_str, message)
    headers={
        'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="{mch_id}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{serial_no}"',
    }
    response = requests.get(UFDODER_URL, headers=headers)
    data_dict = json.loads(response.content)  # 将请求返回的数据转为字典
    print(data_dict)
    if 'message' in data_dict:
        return 1
    url = data_dict['url']
    message = f'GET\n{url.replace("https://api.mch.weixin.qq.com", "")}\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt(pub_key_str, message)

    headers={
        'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="{mch_id}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{serial_no}"',
    }
    response = requests.get(url, headers=headers)
    a = response.content.decode()
    return a


def synchronization_stock_data():
    queryset = AliDiscountCoupon.objects.exclude(is_synchronization=1).filter(coupon_channel=2)
    for query in queryset:
        stock_id = query.template_id
        channel = query.platform
        data = get_data(stock_id, channel.pub_key, channel.mchid, channel.serial_no)
        time.sleep(12)
        if data == 1:
            continue
        publish_start_time = query.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
        publish_end_time = query.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
        table_name = f'tb_stock_data_{query.publish_start_time.strftime("%Y%m")}'
        data = data.split('\r\n')[1:-4]
        if data:
            conn = pymysql.connect(host=settings.DATABASES['stock_data']['HOST'],
                                   port=settings.DATABASES['stock_data']['PORT'],
                                   database=settings.DATABASES['stock_data']['NAME'],
                                   user=settings.DATABASES['stock_data']['USER'],
                                   password=settings.DATABASES['stock_data']['PASSWORD'])
            cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
            try:
                sql = f'''INSERT INTO {table_name}(stock_id,voucher_id,discount_type,discount_amount,order_amount,order_type,transaction_id,pay_time,publish_start_time,publish_end_time,mchid,device_id,bank_number,item_information) VALUES '''
                for i in data:
                    l1 = i.split(',')
                    insert_data = []
                    insert_data.append(l1[0].replace('`', ''))
                    insert_data.append(l1[1].replace('`', ''))
                    insert_data.append(l1[2].replace('`', ''))
                    insert_data.append(l1[3].replace('`', ''))
                    insert_data.append(l1[4].replace('`', ''))
                    insert_data.append(l1[5].replace('`', ''))
                    insert_data.append(l1[6].replace('`', ''))
                    insert_data.append(l1[7].replace('`', ''))
                    insert_data.append(publish_start_time)
                    insert_data.append(publish_end_time)
                    insert_data.append(l1[8].replace('`', ''))
                    insert_data.append(l1[9].replace('`', ''))
                    insert_data.append(l1[10].replace('`', ''))
                    insert_data.append(l1[11].replace('`', ''))
                    sql += str(tuple(insert_data)).replace("'null'", 'null')
                    sql += ','
                sql = sql[:-1]
                sql += ';'
                # print(sql)
                cursor.execute(sql)
                conn.commit()
                query.is_synchronization = 1
                query.save()
                print(table_name)
            except Exception as e:
                print(e)
                conn.rollback()
            cursor.close()
            conn.close()


if __name__ == '__main__':
    synchronization_stock_data()